from app.models.database import db
from datetime import datetime

class Scene(db.Model):
    """场景模型"""
    __tablename__ = 'scene'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    tags = db.Column(db.JSON)  # 存储标签列表
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联到场景步骤，明确指定外键
    steps = db.relationship('SceneStep', back_populates='scene', 
                           foreign_keys='SceneStep.scene_id',
                           order_by='SceneStep.order')
    
    # 关联到执行记录
    records = db.relationship('ExecutionRecord', back_populates='scene')
    
    def to_dict(self):
        # 计算所有步骤的总数（包括顶级步骤和子步骤）
        def count_all_steps(steps):
            count = len(steps)
            for step in steps:
                # 获取当前步骤的所有子步骤
                child_steps = [s for s in self.steps if s.parent_id == step.id]
                count += count_all_steps(child_steps)
            return count
        
        # 获取所有顶级步骤
        top_level_steps = [step for step in self.steps if step.parent_id is None]
        total_steps = count_all_steps(top_level_steps)
        
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'tags': self.tags or [],
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
            'steps': [step.to_dict() for step in top_level_steps],  # 只返回顶级步骤
            'step_count': total_steps  # 添加步骤总数
        }